package com.renyi.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.renyi.model.MybatisService;
import com.renyi.util.CalendarUtil;

/**
 * 
 * @author zzf
 * 
 */
@Service("tjxmService")
public class TjxmService   {

	@Autowired
	private MybatisService mybatisService;

	private Logger log = LogManager.getLogger(this.getClass().getName());
	
	
	
		@Transactional(readOnly = false, rollbackFor = { DataAccessException.class, Exception.class })
		public int addBlxx(Map<String,Object> params)  throws Exception {
				int key =  0;
				Map<String, Object> pMap = new HashMap<String, Object>();
				pMap.put("sCode", "BLH"); 
				List<HashMap<String, Object>> codeList = this.mybatisService.findMybatisList("getSerialNo",pMap);
				//String BLH =  (String)this.mybatisService.findMybatisObject("getSerialNo",pMap);
				HashMap<String, Object> codeMap =  codeList.get(0);
				
				//得到病人病历信息
				
				List<HashMap<String, Object>> patientUserInfoList = this.mybatisService.findMybatisList("getPatientUserInfo",params);
				if(patientUserInfoList ==null || patientUserInfoList.size() == 0){
					return -1;
				}
				HashMap<String, Object> patientUser =  patientUserInfoList.get(0);
				
				String now =  CalendarUtil.Now();
				params.put("BLH", codeMap.get("result"));//病历号
				params.put("CJSJ", now);//就诊日期
				params.put("JZRQ",now);//就诊日期
				params.put("BRID", patientUser.get("BRID")); 
				params.put("XB",  patientUser.get("XB")); 
				params.put("NLDW",  patientUser.get("NLDW"));//APP 
				params.put("BLLY", 1);//APP 
				int count	 =   (Integer)this.mybatisService.insertIbatisObject("addBlxx", params);
				if(count>0){
					key =  Integer.parseInt(params.get("ID").toString());
					/*检查明细*/
					 String JCMX = params.get("JCMX")!=null?params.get("JCMX").toString():"";
						ArrayList<Map<String,Object>> jcmxList = new ArrayList<Map<String,Object>>();
						JSONArray jcmxAry =   JSON.parseArray(JCMX);
				 		for(Object obj:jcmxAry){ 
				 			JSONObject jObj = (JSONObject)obj;
				 			HashMap<String,Object> hm  = new HashMap<String,Object>();
				 			hm.put("BLID", key);
				 			hm.put("XMID", jObj.get("XMID"));
				 			hm.put("XMMC", jObj.get("XMMC"));
				 			hm.put("JG", jObj.get("JG"));
				 			hm.put("FLLB", jObj.get("FLLB"));
				 			jcmxList.add(hm);
					   }
				 		this.mybatisService.batchIbatisObject("addBlxxJcmx", jcmxList);
				}
			return key;
		}

 
}
